<?php
use Workerman\Worker;
use Workerman\Lib\Timer;
use Beanstalk\Client;
require_once __DIR__ . '/Workerman/Autoloader.php';
require_once __DIR__ . '/Channel/src/Server.php';
require_once __DIR__ . '/Channel/src/Client.php';
require_once __DIR__ . '/mysql/src/Connection.php';  //mysql组件
require_once __DIR__ . '/Beanstalk/Client.php';

// 创建一个Worker监听2345端口，使用http协议通讯
$worker = new Worker("websocket://192.168.32.131:9092");
// 设置实例的名称
$worker->name = 'account';
// 启动4个进程对外提供服务
$worker->count = 20;

$worker->onWorkerStart = function($worker) {
    // Channel\Client::connect('127.0.0.1', 2206);
    Timer::add(0.1, function()use($worker){
        $http=new Http();
        print_r($http->get('http://192.168.32.131/tests'));
    });


};

class Http {

    public static $timeout = 60;
    public static $headers = [];

    public static function post($url, $data = '', $header = []) {
        return static::curl($url, $data, 'post', $header);
    }

    public static function get($url, $data = '') {
        if (is_array($data)) {
            $arr = [];
            foreach ($data as $k => $v) {
                $arr[] = $k . '=' . $v;
            }
            $query = implode('&', $arr);
            $url = $url . '?' . $query;
        }
        return static::curl($url, $data, 'get');
    }

    protected static function curl($url, $data = '', $method = 'post', $header = []) {
        $SSL = substr($url, 0, 8) == "https://" ? true : false;
        $ch = curl_init();
        $options = [
            CURLOPT_URL => $url, //设置请求url
            CURLOPT_TIMEOUT => static::$timeout,
            CURLOPT_CUSTOMREQUEST => strtoupper($method), //设置请求方法
            CURLOPT_RETURNTRANSFER => 1//获取页面内容，不直接输出到页面，而是返回
        ];
        //设置headers
        if (!empty(static::$headers)) {
            $options[CURLOPT_HTTPHEADER] = static::$headers;
        }
        if (!empty($header)) {
            $options[CURLOPT_HTTPHEADER] = $header;
        }
        if ($SSL) {
            $options[CURLOPT_SSL_VERIFYPEER] = false; // 信任任何证书
            $options[CURLOPT_SSL_VERIFYHOST] = 2; // 检查证书中是否设置域名
        }
        if ($method == 'post') {
            $options[CURLOPT_POSTFIELDS] = $data;
        }
        curl_setopt_array($ch, $options);

        $res['body'] = curl_exec($ch);
        $res['request']['params'] = $data;
        $res['request']['url'] = $url;
        $res['env'] = curl_getinfo($ch);
        $res['code'] = $res['env']['http_code'];
        curl_close($ch);
        return $res;
    }

}
Worker::runAll();
